//
//  XJPayViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/6/13.
//  Copyright © 2018年 Tzyang. All rights reserved.
//  付款VC

#import "XJPayViewController.h"
#import "XJPayPasswordViewController.h" // 选择钱包支付先跳转到 支付密码
#import "XJPaySuccessViewController.h" // 付款成功

//view
#import "XJPayHeaderView.h"
#import "XJPaySectionHeaderView.h"
#import "XJPayCell.h"
#import "DCPaymentView.h"
#import "XJRequestFailView.h" // 请求失败的view

//Model
#import "XJPayTypeModel.h"
#import "XJUserModel.h"
#import <AlipaySDK/AlipaySDK.h>



@interface XJPayViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) XJPayHeaderView *headerView;
@property(nonatomic, strong) NSMutableArray *dataArray;
@property(nonatomic, strong) UIView *footerView; // 表尾 立即付款

/**1.账户余额*/
@property (nonatomic, copy) NSString *balance;
/**3.标记选择的支付方式model*/
@property (nonatomic, strong) XJPayTypeModel *selectedPayTypeModel;
/**4.支付密码输入框*/
@property (nonatomic, strong) DCPaymentView *dcPaymentView;
/**5.请求失败要显示的view*/
@property (nonatomic, strong) XJRequestFailView *requestFailView;
@end

@implementation XJPayViewController

#pragma mark - 一 lazy
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView  = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, KWidth, KHeight - kStatusBarAndNavigationBarHeight) style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        // 注册
        [_tableView registerNib:[UINib nibWithNibName:@"XJPayCell" bundle:nil] forCellReuseIdentifier:@"XJPayCell"];
        
        [_tableView registerClass:[XJPaySectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"XJPaySectionHeaderView"];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (XJPayHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[XJPayHeaderView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 150)];
    }
    return _headerView;
}

- (UIView *)footerView {
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 200)];
        
        
        //立即付款按钮
        UIButton *payNowButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [payNowButton setTitle:@"立即付款" forState:(UIControlStateNormal)];
        [payNowButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [payNowButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [payNowButton setBackgroundColor:XJCOLOR_RGB(255, 218, 67)];
        payNowButton.layer.masksToBounds = YES;
        payNowButton.layer.cornerRadius = 10;
        
        CGFloat k30 = 30;
        payNowButton.frame = CGRectMake(k30, k30, KWidth - k30*2, 40);
        [payNowButton addTarget:self action:@selector(payButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
        
        [_footerView addSubview:payNowButton];
    }
    return _footerView;
}

- (DCPaymentView *)dcPaymentView {
    if (!_dcPaymentView) {
        _dcPaymentView = [[DCPaymentView alloc] init];
    }
    return _dcPaymentView;
}

- (XJRequestFailView *)requestFailView {
    if (!_requestFailView) {
        _requestFailView = [[XJRequestFailView alloc] initWithFrame:self.view.bounds];
        XJWeakSelf(self);
        _requestFailView.retryBtnBlock = ^{
            [weakself requestData];
        };
    }
    return _requestFailView;
}


#pragma mark - 一 立即支付

- (void)payButtonAction {
    XJLog(@"立即支付----选择的支付方式是:%@",self.selectedPayTypeModel);
    
    if ([self.selectedPayTypeModel.type isEqualToString:@"balance"]) { // 钱包支付
        
        if ([XJUserModel xj_isPayPassword]) {
            XJLog(@"有支付密码直接支付");
            // 支付成功:跳转支付成功页面
            [self.dcPaymentView show];

            
            XJWeakSelf(self);
            
            self.dcPaymentView.completeHandle = ^(NSString *inputPwd) {
                XJLog(@"密码是:%@",inputPwd);
                [weakself requestPayWithPassword:inputPwd];
            };
            
        }else {

            XJLog(@"跳转设置支付密码页面");
            // 设置完成之后跳转输入支付密码页面。
            XJPayPasswordViewController *payPwdVC = [XJPayPasswordViewController new];
            [self.navigationController pushViewController:payPwdVC animated:YES];
        }
        
    }else if ([self.selectedPayTypeModel.type isEqualToString:@"alipay"]) {
        
        XJLog(@"支付宝支付");
        
        NSString *channel_id = @"alipay_app";
        NSString *foreign_infos = self.foreign_infos;
        NSString *order_amount = self.order_amount;
        NSString *order_type = self.order_type;
        
        NSDictionary *payDic = NSDictionaryOfVariableBindings(channel_id,foreign_infos,order_amount,order_type);
        XJLog(@"%@",payDic);
        
        [self requestPayByZFBWithPayDic:payDic];
        
    }else if ([self.selectedPayTypeModel.type isEqualToString:@"weixin"]) {
        
        XJLog(@"微信支付");
    }else {
        
        XJLog(@"未知付款方式");
    }
    
    
}

#pragma mark - 二 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"付款";
    
    [self requestData];
    
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
    
    self.requestFailView.hidden = YES; //请求失败的时候显示
    [self.view addSubview:self.requestFailView];
}
#pragma mark - 三 UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XJPayCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XJPayCell"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.dataArray[indexPath.row];

    return cell;
}


#pragma mark - 三 UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    XJPaySectionHeaderView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"XJPaySectionHeaderView"];
    
    return sectionHeaderView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 修改按钮的选中状态:1.全部设置为NO. 2.将当前选中的cell的状态设置为YES
    for (XJPayTypeModel *tempM in self.dataArray) {
        tempM.isSel = NO;
    }
    
    XJPayTypeModel *didSelectModel = self.dataArray[indexPath.row];
    didSelectModel.isSel = YES;
    
    [self.tableView reloadData];// ✅ 记得刷新
    
    // 标记选择的支付方式 model
    self.selectedPayTypeModel = didSelectModel;
}

#pragma mark - 四 网络请求
- (void)requestData {
    
    if ([NSString isEmptyString:self.code]) {
        self.code = @"1"; //从其他页面进来传1
    }
    
    NSDictionary *parDic = @{@"order_type":self.order_type, //2 购买商品
                             @"order_amount":self.order_amount, //支付金额
                             @"foreign_infos":self.foreign_infos, // 购买商品则以订单号逗号隔开.
                             @"code":self.code
                             };
    [XJHttpTool requestPayPrepayWithDic:parDic successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if([code isEqualToString:@"0"]) {
            
            NSDictionary *dataDic = responseObjc[@"data"];
            
            self.balance = [NSString stringWithFormat:@"%@",dataDic[@"customer"][@"balance"]]; // 账户余额
            self.order_amount = [NSString stringWithFormat:@"%@",dataDic[@"amount"][@"goods_amount"]];//应付多少钱
            
            //数据源
            NSArray *channelsArr = dataDic[@"channels"];
            self.dataArray =  [self reassembleChannelsArr:channelsArr];
            
            if (self.dataArray.count) {
                
                //标记选择的支付方式model:默认钱包支付
                self.selectedPayTypeModel = [self.dataArray firstObject];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.headerView configureBalance:self.order_amount];
                    [self.tableView reloadData];
                });
            }
            self.requestFailView.hidden = YES;
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
            self.requestFailView.hidden = NO;
        }
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedFailureReason]];
//        XJLog(@"错误:%@",error);
        self.requestFailView.hidden = NO;
    }];
}

// 支付
/**
 {
 "channel_id": "balance",
 "pay_password": "34d61a4c35fa1da91b9cd793c75b41ee",
 "foreign_infos": "SN18061509224500000116",
 "order_amount": "10.0",
 "order_type": "2"  //1为充值,2为购买商品,3为缴费
 }
 */
- (void)requestPayWithPassword:(NSString *)pwd {
    
    NSString *channelId = self.selectedPayTypeModel.type;
    
    //支付密码MD5 小写。
    NSString *md5PwdStr = [self md5PayPasswordAndConvertToLowercase:pwd];
    
    NSString *sn = self.foreign_infos;
        
    NSDictionary *dic = @{@"channel_id":channelId,
                          @"pay_password":md5PwdStr,
                          @"foreign_infos":sn,
                          @"order_amount":self.order_amount,
                          @"order_type":self.order_type
                          };
    
    
    [self rb_showHub];

    [XJHttpTool requestPayWithDic:dic successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
                        //跳转付款成功页面。
            XJPaySuccessViewController *paySuccessVC = [[XJPaySuccessViewController alloc] initWithNibName:@"XJPaySuccessViewController" bundle:nil];
            
            [self presentViewController:paySuccessVC animated:YES completion:nil];
        }else {
            
            [JRToast showWithText:responseObjc[@"message"]];
        }
        
        //隐藏输入框
        [self.dcPaymentView dismiss];

        [self rb_hideHub];
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
        [self rb_hideHub];
        
        //隐藏输入框
        [self.dcPaymentView dismiss];

    }];
}



//服务器返回数据参考
/**
 {
 "data":{
 "amount":Object{...},
 "channels":[
 {
 "type":"balance",
 "channel_id":"balance"
 },
 {
 "type":"alipay",
 "channel_id":"alipay_app"
 },
 {
 "type":"weixin",
 "channel_id":"weixin_app"
 },
 {
 "type":"weixin",
 "channel_id":"weixin_gz"
 }
 ],
 "customer":{
 "balance":0
 }
 },
 "code":0
 }
 */



//支付宝支付方式。
/**
 调用后台支付接口。 请求成功 返回支付参数
 请求成功之后调用支付sdk进行支付。
 
 
 */
- (void)requestPayByZFBWithPayDic:(NSDictionary *)payDic  {
    
    [XJHttpTool requestPayWithDic:payDic successH:^(id responseObjc) {
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        XJLog(@"支付：%@",jsonStr);
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        //调用支付宝SDK进行支付。
        if ([code isEqualToString:@"0"]) {
            NSString *order_info = responseObjc[@"data"][@"pay"][@"params"][@"order_info"];
            XJLog(@"支付宝参数:%@-%ld",order_info,order_info.length);
         NSString *appScheme = @"com.tzyang.cn.XinJiangMall";
//        NOTE: 调用支付结果开始支付
            [[AlipaySDK defaultService] payOrder:order_info fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                NSLog(@"reslut = %@",resultDic);
            }];
        }
        
    } failH:^(NSError *error) {
        XJLog(@"%@",error);
    }];
}

- (void)aliPaySDK {
//     NOTE: 调用支付结果开始支付
//    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
//        NSLog(@"reslut = %@",resultDic);
//    }];

}
#pragma mark - Private method
//MD5 加密后转小写。
- (NSString *)md5PayPasswordAndConvertToLowercase:(NSString *)password {
    NSString *md5Str = [NSString md5:password];
    return md5Str.lowercaseString;
}

// 重新组装数据源数组
- (NSMutableArray *)reassembleChannelsArr:(NSArray *)arr{
    
    // 要干什么?1.剔除 weixin_gz 这个数据 2.转模型 3.对模型再进行二次处理:添加你需要的字段。
    // 选择支付方式。考虑的情况 1.账户余额要先设置支付密码。 2.支付宝直接跳转支付宝支付。3.微信支付跳转微信支付。
    
    //先剔除这个 weixin_gz 对象
    NSMutableArray *newArr = [NSMutableArray array];
    for (NSDictionary *dic in arr) {
        XJPayTypeModel *model = [XJPayTypeModel mj_objectWithKeyValues:dic];
        
        if ([model.channel_id hasSuffix:@"gz"]) {
            XJLog(@"这个不要");
        }else {
            [newArr addObject:model];
        }
    }
    
    // 二次处理:添加icon ，设置默认支付方式。
    
    for (int i=0; i<newArr.count; i++) {
        XJPayTypeModel *model = newArr[i];
        if ([model.type isEqualToString:@"balance"]) { //钱包支付
            model.iconStr = @"pay_money";
            NSString *yuEStr = [NSString stringWithFormat:@"%.1f",self.balance.floatValue];
            model.name = [NSString stringWithFormat:@"余额(%@)",yuEStr];
            model.isSel = YES;
            
        }else if ([model.type isEqualToString:@"alipay"]){ //支付宝
            model.iconStr = @"pay_alipay";
            model.name = @"支付宝支付";
            model.isSel = NO;
            
        }else { // 微信
            model.iconStr = @"pay_WeChat";
            model.name = @"微信支付";
            model.isSel = NO;
        }
    }
    return newArr;
}

- (void)rb_showHub{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}
- (void)rb_hideHub {
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}

@end
